package com.lagou.controller;


import com.alibaba.fastjson.JSON;
import com.lagou.entity.EduConstant;
import com.lagou.entity.Token;
import com.lagou.entity.UserDTO;
import com.lagou.entity.UserId;
import com.lagou.service.UserService;

import com.lagou.tools.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Reference;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 */
@RestController
@RequestMapping("user")
@CrossOrigin
public class WxLoginController {

    @Autowired //远程调用
    private UserService userService;


    @GetMapping("wxlogin")
    public UserDTO wxlogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //微信官方给我们的临时凭证
        String code = request.getParameter("code");
        System.out.println("【临时凭证】code=" + code);

        //通过code去微信官方申请一个正式的令牌（token）
        //发出一个get请求，httpclient-封装好的操作
        //微信官方文档上获得token令牌的请求

        String getTokenByCode_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd99431bbff8305a0&secret=60f78681d063590a469f1b297feff3c4&code=" + code + "&grant_type=authorization_code";

        String tokenString = HttpClientUtil.doGet(getTokenByCode_url);

        System.out.println(tokenString);

        //将json格式的该token字符串转换成实体对象，方便存和取
        Token token = JSON.parseObject(tokenString, Token.class);

        //通过token，去微信官方获取用户的信息
        String getUserByToken = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.getAccess_token() + "&openid=" + token.getOpenid();

        System.out.println("----------------------");
        String UserString = HttpClientUtil.doGet(getUserByToken);
        System.out.println("UserString = " + UserString);


        //将json格式的用户字符串转换成实体对象，方便存和取
        //记得User类的对应的包是对应的
        UserId user = JSON.parseObject(UserString, UserId.class);
        System.out.println("微信的用户昵称 = " + user.getNickname());
        System.out.println("微信的用户头像 = " + user.getHeadimgurl());



        System.out.println("微信的unionid参数值：" + user.getUnionid());

        //检测手机号是否注册
        UserDTO dto = userService.login(user.getUnionid(),user.getUnionid());
        if (dto.getState() == EduConstant.ERROR_NOT_FOUND_PHONE_CODE) {
            //未注册，注册并登录
            userService.register(user.getUnionid(), user.getUnionid(), user.getNickname(), user.getHeadimgurl());
            dto = userService.login(user.getUnionid(), user.getUnionid());
        }


        response.sendRedirect("http://localhost:8080/#/?token="+dto.getToken());

        return null;
    }





}
